package com.wmlive.hhvideo.heihei.discovery.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.os.ResultReceiver;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.dyuiapi.api.model.MusicInfo;
import com.wmlive.hhvideo.common.AppCacheFileUtils;
import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.common.base.DcBaseActivity;
import com.wmlive.hhvideo.common.navigator.Navigator;
import com.wmlive.hhvideo.common.network.HttpConstant;
import com.wmlive.hhvideo.heihei.beans.discovery.MusicContentListBean;
import com.wmlive.hhvideo.heihei.beans.discovery.TopicContentListBean;
import com.wmlive.hhvideo.heihei.beans.main.MultiTypeVideoBean;
import com.wmlive.hhvideo.heihei.beans.main.ShareInfo;
import com.wmlive.hhvideo.heihei.beans.main.ShortVideoItem;
import com.wmlive.hhvideo.heihei.beans.subject.TopicInfo;
import com.wmlive.hhvideo.heihei.channel.ShareSdkUtils;
import com.wmlive.hhvideo.heihei.discovery.adapter.TopicAdapter;
import com.wmlive.hhvideo.heihei.discovery.presenter.TopicPresenter;
import com.wmlive.hhvideo.heihei.discovery.widget.MusicHeader;
import com.wmlive.hhvideo.heihei.discovery.widget.TopicHeader;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.heihei.mainhome.activity.VideoListActivity;
import com.wmlive.hhvideo.heihei.mainhome.fragment.RecommendFragmentNew;
import com.wmlive.hhvideo.heihei.personal.util.SpaceItemDecoration;
import com.wmlive.hhvideo.heihei.recordvideo.DyUIAPIManager;
import com.wmlive.hhvideo.heihei.recordvideo.MusicCustomExtraInfo;
import com.wmlive.hhvideo.utils.MyClickListener;
import com.wmlive.hhvideo.utils.PopupWindowUtils;
import com.wmlive.hhvideo.utils.download.DLog;
import com.wmlive.hhvideo.utils.download.Download;
import com.wmlive.hhvideo.widget.refreshrecycler.OnFooterClickListener;
import com.wmlive.hhvideo.widget.refreshrecycler.OnRecyclerItemClickListener;
import com.wmlive.hhvideo.widget.refreshrecycler.RefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.wmlive.hhvideo.R;

/**
 * Created by lsq on 6/1/2017.
 * 音乐、话题详情页面
 */

public class TopicActivity extends DcBaseActivity<TopicPresenter> implements
        RefreshRecyclerView.OnLoadMoreListener,
        TopicPresenter.ITopicView,
        TopicHeader.OnHeaderClickListener,
        OnRecyclerItemClickListener<ShortVideoItem>, MusicHeader.OnMusicUseListener {
    @BindView(R.id.recyclerView)
    RefreshRecyclerView recyclerView;
    private TopicAdapter topicAdapter;
    private PopupWindow shareWindow;
    private TopicHeader topicHeader;     //话题的头部
    private MusicHeader musicHeader;     //音乐的头部
    private long topicId; //话题的id
    private long musicId;//音乐的id
    private boolean isTopic; //true是话题，false是音乐
    private MenuItem menuCollect;
    private MenuItem menuShare;
    private ShareInfo shareInfoBean;
    private ImageView ivCollect;
    private ImageView ivShare;

    /**
     * 话题类型
     *
     * @param context
     * @param topicId 话题的id
     */
    public static void startTopicActivity(Context context, long topicId) {
        Intent intent = new Intent(context, TopicActivity.class);
        intent.putExtra("topicId", topicId);
        context.startActivity(intent);
    }

    /**
     * 音乐类型
     *
     * @param context
     * @param musicId 音乐的id
     */
    public static void startMusicActivity(Context context, long musicId) {
        Intent intent = new Intent(context, TopicActivity.class);
        intent.putExtra("musicId", musicId);
        context.startActivity(intent);
    }


    @Override
    protected void onSingleClick(View v) {

    }

    @Override
    protected TopicPresenter getPresenter() {
        return new TopicPresenter(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_topic;
    }

    @Override
    protected void initData() {
        super.initData();

        topicId = getIntent().getLongExtra("topicId", 0);
        musicId = getIntent().getLongExtra("musicId", 0);
        if (musicId > 0) {
            isTopic = false;
            setRelativeMode(true);
            setTitle("", true);
            toolbar.setAllBackgroundColor(Color.argb(0, 0, 0, 0));
        } else if (topicId > 0) {
            setRelativeMode(true);
            setTitle("", true);
            toolbar.setAllBackgroundColor(Color.argb(0, 0, 0, 0));
            isTopic = true;
        } else {
            toastFinish();
            return;
        }

        View view = LayoutInflater.from(this).inflate(R.layout.view_share_colloct_menu, toolbar, false);
        toolbar.addRightView(view, null);
        ivCollect = (ImageView) view.findViewById(R.id.ivCollect);
        ivCollect.setVisibility(!isTopic ? View.VISIBLE : View.GONE);
        ivCollect.setOnClickListener(new MyClickListener() {
            @Override
            protected void onMyClick(View v) {
                if (!TextUtils.isEmpty(AccountUtil.getToken())) {
                    presenter.addFavorite(0, musicId);
                } else {
                    showReLogin();
                }
            }
        });

        ivShare = (ImageView) view.findViewById(R.id.ivShare);
        ivShare.setOnClickListener(new MyClickListener() {
            @Override
            protected void onMyClick(View v) {
                shareWindow = PopupWindowUtils.showMusicShare(TopicActivity.this, toolbar, shareClick);
            }
        });

        recyclerView.setRefreshEnable(false);
        topicAdapter = new TopicAdapter(new ArrayList(), recyclerView);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return position == 0 ? 3 : 1;
            }
        });
        recyclerView.setLayoutManager(layoutManager);
        topicAdapter.setOnRecyclerItemClickListener(this);
        recyclerView.addItemDecoration(new SpaceItemDecoration(8, true));
        recyclerView.setAdapter(topicAdapter);
        recyclerView.setOnLoadMoreListener(this);
        recyclerView.setOnFooterClickListener(new OnFooterClickListener() {
            @Override
            public void onPageErrorClick() {
                super.onPageErrorClick();
                if (isTopic) {
                    presenter.getTopicList(true, topicId);
                } else {
                    presenter.getMusicList(true, musicId);
                }
            }

            @Override
            public void onFootErrorClick() {
                super.onFootErrorClick();
                onLoadMore();
            }
        });
        if (isTopic) {
            topicHeader = new TopicHeader(this);
            recyclerView.setHeader(topicHeader);
        } else {
            musicHeader = new MusicHeader(this);
            recyclerView.setHeader(musicHeader);
        }
        if (isTopic) {
            presenter.getTopicList(true, topicId);
        } else {
            presenter.getMusicList(true, musicId);
        }
    }

    @Override
    public void onLoadMore() {
        if (isTopic) {
            presenter.getTopicList(false, topicId);
        } else {
            presenter.getMusicList(false, musicId);
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
//        menuShare = menu.findItem(R.id.itemShare);
//        menuCollect = menu.findItem(R.id.itemCollect);
//        menuCollect.setVisible(!isTopic);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_topic_share, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case R.id.itemShare:
//                shareWindow = PopupWindowUtils.showMusicShare(this, toolbar, shareClick);
//                break;
//            case R.id.itemCollect:
//                presenter.addFavorite(0, musicId);
//                break;
//        }
        return super.onOptionsItemSelected(item);
    }

    private MyClickListener shareClick = new MyClickListener() {
        @Override
        protected void onMyClick(View v) {
            if (null != topicAdapter && null != topicAdapter.getDataContainer() && topicAdapter.hasContent()) {
                if (topicAdapter.isContent(0)) {
                    if (shareInfoBean == null) {
                        shareInfoBean = new ShareInfo();
                    }
                    shareInfoBean.setShare_image_url(topicAdapter.getDataContainer().get(0).getOpus_small_cover());
                }
            }
            switch (v.getId()) {
                case R.id.llWeChat:
                    ShareSdkUtils.getInstance().showWechatShare(TopicActivity.this, shareInfoBean, null);
                    break;
                case R.id.llCircle:
                    ShareSdkUtils.getInstance().showWechatMomentsShare(TopicActivity.this, shareInfoBean, null);
                    break;
                case R.id.llWeibo:
                    ShareSdkUtils.getInstance().showWeiboShare(TopicActivity.this, shareInfoBean, null);
                    break;
                case R.id.llQQ:
                    ShareSdkUtils.getInstance().showQQShare(TopicActivity.this, shareInfoBean, null);
                    break;
                case R.id.llCopy:
                    if (shareInfoBean != null && !TextUtils.isEmpty(shareInfoBean.getShare_url())) {
                        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        cm.setText(shareInfoBean.getShare_url());
                        showToast(R.string.copy_succeed);
                    } else {
                        showToast("数据错误，复制链接失败");
                    }
                    break;
            }
            if (null != shareWindow) {
                shareWindow.dismiss();
            }
        }
    };

    @Override
    public void onJoinTopicClick(TopicContentListBean.TopicInfoBean topicInfoBean) {
        if (topicInfoBean != null && topicId > 0) {
            if (!TextUtils.isEmpty(AccountUtil.getToken())) {
                TopicInfo topicInfo = new TopicInfo();
                topicInfo.setMstrTopic(topicInfoBean.getName());
                topicInfo.setMstrText(topicInfoBean.getDescription());
                topicInfo.setmTopicId(Long.valueOf(topicInfoBean.getId()));
                SearchMusicVideoActivity.startSearchMusicActivity(this, topicInfo);
            } else {
                showReLogin();
            }
        } else {
            showToast(R.string.hintErrorDataDelayTry);
        }
    }

    @Override
    public void onAvatarClick(TopicContentListBean.TopicInfoBean topicInfoBean) {
        if (null != topicInfoBean && topicInfoBean.getCreator_id() > 0) {
            Navigator.getInstance().navigateToOtherUserHome(this, false, topicInfoBean.getCreator_id());
        } else {
            showToast(R.string.hintErrorDataDelayTry);
        }
    }

    @Override
    public void onUseMusicClick(MusicContentListBean.MusicInfoBean bean) {
        if (bean != null && !TextUtils.isEmpty(bean.getMusic_path())) {
            if (!TextUtils.isEmpty(AccountUtil.getToken())) {
                downloadMusic(bean);
            } else {
                showReLogin();
            }
        } else {
            showToast(R.string.hintErrorDataDelayTry);
        }
    }

    //下载音乐
    private void downloadMusic(final MusicContentListBean.MusicInfoBean bean) {
        DLog.setDebug(GlobalParams.Config.IS_DEBUG);
        Download.start(this, bean.getMusic_path(), AppCacheFileUtils.getAppMusicCachePath(), "",
                new ResultReceiver(new Handler(getMainLooper())) {
                    @Override
                    protected void onReceiveResult(int resultCode, Bundle resultData) {
                        String message = resultData.getString("message");
                        switch (resultCode) {
                            case Download.RESULT_PREPARE:
                                loading(true, new DialogInterface.OnDismissListener() {
                                    @Override
                                    public void onDismiss(DialogInterface dialog) {
                                        Download.pause(TopicActivity.this);
                                    }
                                });
                                break;
                            case Download.RESULT_PAUSE:
                                dismissLoad();
                                break;
                            case Download.RESULT_DOWNLOADING:
                                break;
                            case Download.RESULT_ERROR:
                                dismissLoad();
                                showToast(message);
                                break;
                            case Download.RESULT_COMPLETE:
                                dismissLoad();
                                MusicCustomExtraInfo userMusicInfoExtraInfo = new MusicCustomExtraInfo();
                                userMusicInfoExtraInfo.setMusicId(Long.parseLong(bean.getId()));
                                MusicInfo musicInfo = new MusicInfo(resultData.getString("savePath"), bean.getAlbum_cover(), bean.getName(), bean.getSinger_name(), userMusicInfoExtraInfo);
                                // musicInfo.setExtraInfo(userMusicInfoExtraInfo);
                                DyUIAPIManager.getInstance().onCameraByMusicInfo(TopicActivity.this, musicInfo, false);
                                break;
                        }
                    }
                });
    }

    @Override
    public void onTopicInfoOk(TopicContentListBean.TopicInfoBean bean) {
        if (bean != null) {
            shareInfoBean = bean.getShare_info();
            ivShare.setVisibility(null != shareInfoBean ? View.VISIBLE : View.GONE);
            topicHeader.setData(bean).setClickListener(this);
        }
    }

    @Override
    public void onTopicListOk(boolean isRefresh, List<ShortVideoItem> list, boolean hasMore) {
        topicAdapter.addData(isRefresh, list, hasMore);
        ivShare.setVisibility(topicAdapter.hasContent() ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onRequestDataError(int requestCode, String message) {
        if (requestCode == HttpConstant.TYPE_DISCOVERY_MUSIC_LIST
                || (requestCode == HttpConstant.TYPE_DISCOVERY_MUSIC_LIST + 1)) {
            topicAdapter.showError(requestCode == HttpConstant.TYPE_DISCOVERY_MUSIC_LIST);
        } else if (requestCode == HttpConstant.TYPE_DISCOVERY_TOPIC_LIST
                || requestCode == (HttpConstant.TYPE_DISCOVERY_TOPIC_LIST + 1)) {
            topicAdapter.showError(requestCode == HttpConstant.TYPE_DISCOVERY_TOPIC_LIST);
        } else if (requestCode == HttpConstant.TYPE_DISCOVERY_ADD_FAVORITE) {
            showToast("收藏失败，请稍后再试");
        } else {
            super.onRequestDataError(requestCode, message);
        }
        ivShare.setVisibility(topicAdapter.hasContent() ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onMusicInfoOk(MusicContentListBean.MusicInfoBean bean) {
        if (null != bean) {
            shareInfoBean = bean.getShare_info();
            ivCollect.setImageResource(bean.isIs_favorite() ? R.drawable.icon_collect_sel : R.drawable.icon_collect);
        }
        ivShare.setVisibility(null != shareInfoBean ? View.VISIBLE : View.GONE);
        musicHeader.setData(bean).setOnMusicUseListener(this);
    }

    @Override
    public void onMusicListOk(boolean isRefresh, List<ShortVideoItem> list, boolean hasMore) {
        topicAdapter.addData(isRefresh, list, hasMore);
        ivShare.setVisibility(topicAdapter.hasContent() ? View.VISIBLE : View.GONE);
    }


    @Override
    public void onAddFavoriteResult(int position, boolean ok) {
        showToast(ok ? "已收藏" : "取消收藏");
        ivCollect.setImageResource(ok ? R.drawable.icon_collect_sel : R.drawable.icon_collect);
    }

    @Override
    public void onRecyclerItemClick(int dataPosition, View view, ShortVideoItem data) {
        if (data != null) {
            if (isTopic) {
                VideoListActivity.startActivity(this, RecommendFragmentNew.TYPE_TOPIC, MultiTypeVideoBean.createTopicParma(topicId, dataPosition, topicAdapter.getDataContainer()));
            } else {
                VideoListActivity.startActivity(this, RecommendFragmentNew.TYPE_MUSIC, MultiTypeVideoBean.createMusicParma(musicId, dataPosition, topicAdapter.getDataContainer()));

            }
        } else {
            showToast(R.string.hintErrorDataDelayTry);
        }
    }

}
